﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace WHLRDF.ORM
{
    public class CustomArgs
    {
        public bool Cancel = false;
    }
    /// <summary>
    /// 操作类型
    /// </summary>
    public enum EntityState
    {
        /// <summary>
        /// 无操作
        /// </summary>
        None=0,
        /// <summary>
        /// 新增操作
        /// </summary>
        Add=1,
        /// <summary>
        /// 修改操作
        /// </summary>
        Update=2,
        /// <summary>
        /// 删除操作
        /// </summary>
        Delete=3

    }
   
    public class EntityBase
    {

    
        public delegate void CustomEventHandler(EntityBase sender, CustomArgs e);

        /// <summary>
        /// OnLoaded事件，在实体查找后触发
        /// </summary>
        public event CustomEventHandler OnLoaded;

        /// <summary>
        /// OnInserted事件，在实体插入过程后触发
        /// </summary>
        public event CustomEventHandler OnInserted;

        /// <summary>
        /// OnUpdated事件，在实体更新过程后触发
        /// </summary>
        public event CustomEventHandler OnUpdated;


        /// <summary>
        /// OnDeleted事件，在实体更新过程后触发
        /// </summary>
        public event CustomEventHandler OnDeleted;
        /// <summary>
        /// 创建人
        /// </summary>
        public const string __CreateBy = "CreateBy";

        /// <summary>
        /// 创建时间
        /// </summary>
        public const string __CreateDate = "CreateDate";

        /// <summary>
        /// 修改人
        /// </summary>
        public const string __LastModifyUserId = "LastModifyUserId";

        /// <summary>
        /// 修改人
        /// </summary>
        public const string __LastModifyDate = "LastModifyDate";


        /// <summary>
        /// 逻辑删除标识
        /// </summary>
        public const string __IsDeleted = "IsDeleted";

        private string _createBy;
        private DateTime _createDate = DateTime.Now;
        private string _lastModifyUserId ;
        private DateTime _lastModifyDate = DateTime.Now;
        private bool _isDeleted = false;
      
        [DbColumn("CreateBy", LocalName = "创建人", AllowDBNull = false, IsSystem = true, IsHide = true, Update = false,ColumnType ="string")]
        public virtual string CreateBy
        {
            get
            {

                return _createBy;
            }
            set { SetData(__CreateBy,value); _createBy = value; }
        }
        [DbColumn("CreateDate", LocalName = "创建时间", AllowDBNull = false, IsSystem = true, IsHide = true, ColumnType = "date", Format = "yyyy-MM-dd hh:mm:ss", Update = false)]
        [JsonProperty]
        public virtual DateTime CreateDate
        {
            get
            {
               return _createDate; 
            }
            set {
                SetData(__CreateDate, value);
                _createDate = value; }
        }

        [DbColumn("LastModifyUserId", LocalName = "修改人", AllowDBNull = false, IsSystem = true, IsHide = true, ColumnType = "string")]
        [JsonProperty]
        public virtual string LastModifyUserId
        {
            get
            {
                return _lastModifyUserId;
            }
            set { SetData(__LastModifyUserId,value); _lastModifyUserId = value; }
        }

        [DbColumn("LastModifyDate", LocalName = "修改时间", AllowDBNull = false, ColumnType = "date", GridWidth = 150, IsSystem = true, Format = "yyyy-MM-dd hh:mm:ss")]
        [JsonProperty]
        public virtual DateTime LastModifyDate
        {
            get
            {
                return _lastModifyDate;
            }
            set { SetData(__LastModifyDate,value); _lastModifyDate = value; }
        }
        [DbColumn("IsDeleted", LocalName = "是否删除", AllowDBNull = false, Default = "false", IsSystem = true, IsHide = true, ColumnType = "bool")]
        [JsonProperty]
        public virtual bool IsDeleted { get { return _isDeleted; } set { _isDeleted = value; } }
      

        [JsonIgnore]
        /// <summary>
        /// 更新字段
        /// </summary>
        public virtual Dictionary<string, object> DataCollection { get; set; } = new Dictionary<string, object>();

        [JsonIgnore]
        /// <summary>
        /// 表名
        /// </summary>
        public virtual string TableName { get; set; }
        [JsonIgnore]
        public virtual string PrimaryKeyName { get; set; }
        private EntityState _state;
        /// <summary>
        /// 实体操作类型
        /// </summary>
        public EntityState State
        {
            get
            {
                return _state;
            }
            set
            {
                _state = value;
            }
        }

        public EntityBase()
        {
            
        }
        /// <summary>
        /// 设置变更属性值
        /// </summary>
        /// <param name="field"></param>
        /// <param name="value"></param>
        public virtual void SetData(string field, object value)
        {
            DataCollection[field] = value;
        }

        ///// <summary>
        ///// 给字段赋值
        ///// </summary>
        ///// <param name="fieldName"></param>
        ///// <param name="value"></param>
        //public virtual Dictionary<string, string> ValidData( )
        //{
        //    ApplyInstance();
        //    Dictionary<string, string> modelState = new Dictionary<string, string>();
        //    if (DataCollection != null && DataCollection.Count > 0)
        //    {
        //        foreach (var item in DataCollection)
        //        {
        //            string strError = "";
        //            var dbField = this.DbFields.Where(x => x.Name == item.Key).FirstOrDefault();
        //            if (dbField != null)
        //            {
        //                if (!CheckValidHelper.CheckDbColumn(dbField, item.Value != null ? item.Value.ToString() : "", ref strError))
        //                {
        //                    modelState.Add(item.Key, strError);
                       
        //                }
                    
        //            }
        //        }
        //    }
        //    return modelState;

        //}
     
        #region  构建其它条件
      
        #endregion

        [JsonIgnore]
        /// <summary>
        /// 数据库引擎
        /// </summary>
        public IDbRepository DbRepository { get; set; }

        #region --实体操作--
        public virtual Dictionary<string, string> CheckValid()
        {
            DataProxy dataProxy = new DataProxy(this.GetType());
            return dataProxy.CheckValid(this);

        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns>自动递增列的最大值 -1插入失败</returns>
        public bool Insert(ref string strError, DataProxy dataProxy = null)
        {
            if (dataProxy == null)
            {
                dataProxy = new DataProxy(this.GetType());
            }
            if (dataProxy.Insert(this, ref strError))
            {
                if (OnInserted != null)
                {
                    OnInserted(this, null);
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <returns></returns>
        public bool Update(ref string strError, DataProxy dataProxy=null)
        {
            if (dataProxy == null)
            {
                dataProxy = new DataProxy(this.GetType());
            }
            if (dataProxy.Update(this, ref strError))
            {
                if (OnUpdated != null)
                {
                    OnUpdated(this, null);
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// 判断此实体在数据库中是否存在
        /// </summary>
        /// <returns></returns>
        public bool Exist(DataProxy dataProxy = null)
        {
            if (dataProxy == null)
            {
                dataProxy = new DataProxy(this.GetType());
            }
            // ReflectionHelper.CheckCallingAssembly(Assembly.GetCallingAssembly());
            return dataProxy.IsExist(DbRepository,this);
        }
        /// <summary>
        /// 保存数据，包含一层子集合
        /// </summary>
        /// <returns> </returns>
        public bool Save(ref string strError)
        {
            DataProxy dataProxy = new DataProxy(this.GetType());
            if (State == EntityState.None)
            {
                State = EntityState.Add;
                if (Exist(dataProxy))
                {
                    State = EntityState.Update;
                }
            }
            if (State == EntityState.Add)
            {
                return this.Insert(ref strError, dataProxy);
            }
            else if (State == EntityState.Delete)
            {
                return this.Delete(ref strError, dataProxy);
            }
            else
            {
                return this.Update(ref strError, dataProxy);
            }
           
        }
        /// <summary>
        /// 删除数据，包含一层子集合
        /// </summary>
        /// <returns></returns>
        public bool Delete(string id,ref string strError)
        {
           var dataProxy = new DataProxy(this.GetType());
            if (string.IsNullOrWhiteSpace(id))
            {
                strError = "主键为空不能删除";
                return false;
            }
            dataProxy.SetValue(this, dataProxy.PrimaryKeyName, id);
            if (dataProxy.Delete(this, null, ref strError))
            {
                if (OnDeleted != null)
                {
                    OnDeleted(this, null);
                }
                return true;
            }

            return false;
        }
        /// <summary>
        /// 删除数据，包含一层子集合
        /// </summary>
        /// <returns></returns>
        public bool Delete(ref string strError,DataProxy dataProxy = null)
        {
            if (dataProxy == null)
            {
                dataProxy = new DataProxy(this.GetType());
            }
            if (dataProxy.Delete(this, null, ref strError))
            {
                if (OnDeleted != null)
                {
                    OnDeleted(this, null);
                }
                return true;
            }

            return false;
        }

        /// <summary>
        /// 装载数据，包含一层子集合
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Retrieve()
        {
            DataProxy dataProxy = new DataProxy(this.GetType());
            object id = dataProxy.GetPrimaryValue(this);
            if (id == null || string.IsNullOrWhiteSpace(id.ToString()))
            {
                return false;
            }
           var criterion = Expression.Eq(dataProxy.PrimaryKeyName, id);
            if (Retrieve(criterion))
            {
                if (OnLoaded != null)
                {
                    OnLoaded(this, null);
                }
                return true;
            }
            return false;
        }


        /// <summary>
        /// 查询单个实体
        /// </summary>
        /// <param name="criterion"></param>
        /// <returns></returns>
        public bool Retrieve(ICriterion criterion)
        {
            DataProxy dataProxy = new DataProxy(this.GetType());
            return Retrieve(dataProxy,criterion);
        }
        /// <summary>
        /// 查询单个实体
        /// </summary>
        /// <param name="criterion"></param>
        /// <returns></returns>
        public bool Retrieve(DataProxy dataProxy,ICriterion criterion)
        {
            
            bool rtn = false;
            string strError = "";
            rtn = dataProxy.Load(this, criterion, ref strError);
            if (rtn)
            {
                if (OnLoaded != null)
                {
                    OnLoaded(this, null);
                }
            }
            return rtn;
        }
        #endregion

    }

}
